import { useLoginApi, useLoginUserApi } from '@/api/auth';
import type { ILoginUser, IProject } from '@/types/user';
import { defineStore } from 'pinia';
import cache from '@/utils/cache';
export const useUserStore = defineStore('userStore', {
  state: () => ({
    token: cache.getToken(),
    refreshToken: '',
    user: cache.getUser(),
    project: cache.getProject(), //当前选中的项目信息
    roleLit: [],
    teamList: [],
  }),
  actions: {
    //设置token
    setToken(value: string) {
      this.token = value;
      cache.setToken(value);
    },
    removeToken() {
      cache.removeToken();
    },
    setRefreshToken(value: string) {
      this.refreshToken = value;
    },
    //设置用户信息
    setUser(value: ILoginUser) {
      this.user = value;
      cache.setUser(value);
    },
    getUser(): ILoginUser {
      return this.user;
    },
    removeUser() {
      cache.removeUser();
    },
    setProject(value: IProject) {
      this.project = value;
      cache.setProject(value);
    },
    getProject() {
      return this.project;
    },
    removePoject() {
      cache.removeUser();
    },

    async login(loginCode: string, loginPassword: string) {
      const { data } = await useLoginApi(loginCode, loginPassword);
      const result = data as unknown as { token: string };
      this.setToken(result.token);
      await this.loginUser();
      window.location.href = './';
    },

    async loginUser() {
      const result = await useLoginUserApi();
      const data = result.data as unknown as { loginUser: ILoginUser; project: IProject };
      this.setUser(data.loginUser);
    },
  },
});
